package com.ruoyi.jvm.gc;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ReferenceDome {
    public static void main(String[] args) {
        /*强引用*/
        /*Student student = new Student();
        student = null;
        System.gc();*/

        /*软引用就是把对象用SoftReference包裹一下，当我们需要从软引用对象获得包裹的对象，只要get一下*/
//        SoftReference<Student> studentSoftReference = new SoftReference<Student>(new Student());
        /*SoftReference<byte[]> softReference = new SoftReference<byte[]>(new byte[1024*1024*10]);
        System.out.println(softReference.get());
        System.gc();
        System.out.println(softReference.get());*/

        /*当内存不足，会触发JVM的GC，如果GC后，内存还是不足，就会把软引用的包裹的对象给干掉，
        也就是只有在内存不足，JVM才会回收该对象。*/
        /*-Xmx20M*/
        /*byte[] bytes = new byte[1024 * 1024 * 10];
        System.out.println(softReference.get());*/

        /*虚引用必须与ReferenceQueue一起使用*/
        ReferenceQueue queue = new ReferenceQueue();
        List<byte[]> bytes = new ArrayList<>();
        PhantomReference<Student> reference = new PhantomReference<Student>(new Student(),queue);
        new Thread(() -> {
            for (int i = 0; i < 100;i++ ) {
                bytes.add(new byte[1024 * 1024]);
            }
        }).start();

        new Thread(() -> {
            while (true) {
                Reference poll = queue.poll();
                if (poll != null) {
                    System.out.println("虚引用被回收了：" + poll);
                }
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        scanner.hasNext();
    }
}

class Student {

    @Override
    protected void finalize() throws Throwable {
        System.out.println("Student对象 被回收了");
    }
}
